package com.qf.controller;

import com.qf.bean.User;
import com.qf.constant.SSMConstant;
import com.qf.service.UserService;
import com.sun.org.apache.regexp.internal.RE;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户模块的controller.
 * @author yao
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private final String CODE = "USERCODE";

    private final String REGISTER_PAGE = "user/register";

    private final String LOGIN_PAGE = "user/login";

    @Autowired
    private UserService userService;

    @Value("${apikey}")
    private String apikey;


    @RequestMapping("/login")
    public String login(String username,String password,HttpSession session,
                        Model model){
        //1. 判断参数是否合法.
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            // 参数不合法.
            return LOGIN_PAGE;
        }
        //2. 参数合法 = 执行登录操作.
        User user = userService.login(username,password);
        if(user != null){
            session.setAttribute(SSMConstant.USER,user);
            return "redirect:/item/list";
        }else{
            // 用户名或密码错误
            // 给用户一些提示
            model.addAttribute("loginInfo","用户名或密码错误!");
            return LOGIN_PAGE;
        }


    }


    // 发送手机短信     http://localhost/user/sendsms
    @RequestMapping("/sendsms")
    @ResponseBody
    public String sendSms(@RequestParam String phone, HttpSession session) {
        // 获取6位数验证码
        String code = (int)((Math.random()*9+1)*100000) + "";
        // 将正确的验证码放到session中
        session.setAttribute(CODE,code);
        //初始化clnt,使用单例方式
        YunpianClient clnt = new YunpianClient(apikey).init();
        //发送短信API
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, phone);
        param.put(YunpianClient.TEXT, "【云片网】您的验证码是" + code);
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
        //释放clnt
        clnt.close();
        return "ok";
    }


    /*
               jsonlib.           很少用了.
               jackson.           spring默认支持jackson.   3个jar包.
               gson.              spring默认支持gson,但是更推荐jackson.
               fastJSON.          号称速度最快的json序列化工具.
    */
    // 异步校验用户名.  http://localhost/user/checkusername
    // 接收json参数.    {username:admin}     {"data": 1}
    @RequestMapping("/checkusername")
    @ResponseBody    // 返回数据不通过视图解析器,直接响应给浏览器.
    public Map<String, Object> checkUsername(@RequestBody User user) {
        //1. 获取用户名.
        String username = user.getUsername();
        //2. 调用service判断是否可用
        Integer count = userService.checkUsername(username);
        //3. 响应数据
        Map<String, Object> result = new HashMap<>();
        result.put("data", count);
        return result;
    }


    // 跳转到注册页面   method = {RequestMethod.POST,RequestMethod.GET}
    @RequestMapping(value = "/register")
    public String register(@Valid User user, BindingResult bindingResult,
                           String registerCode,HttpSession session) {
        // 1. 判断参数.
        if(StringUtils.isEmpty(registerCode) || bindingResult.hasErrors()){
            // 参数不合法.
            return REGISTER_PAGE;
        }

        // 2. 判断验证码是否正确
        String userCode = (String) session.getAttribute(CODE);
        if(registerCode.equals(userCode)){
            // 验证码正确   开始注册功能.
            Integer count = userService.register(user);
            if(count == 1){
                // 注册成功.
                return "redirect:/user/login";
            }
        }
        // 转发到注册页面
        return REGISTER_PAGE;
    }

}
